#include "toast.h"
#include <QTimer>
#include <QLabel>
#include <QVBoxLayout>
#include <QApplication>
#include <QScreen>
#include "util.h"

Toast::Toast(const QString &text)
{
    initUI(text);
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        timer->stop();
        this->close();
        this->deleteLater();
    });
    timer->start(2000);
}

Toast::Toast(const QString &text, QWidget *widget)
{
    initUI(text);
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        timer->stop();
        this->close();
        this->deleteLater();
        if(widget) {
            widget->show();
        }
    });
    timer->start(2000);
}

void Toast::showMessage(const QString &text)
{
    Toast* toast = new Toast(text);
    toast->show();
}

void Toast::showMessage(const QString &text, QWidget *widget)
{
    Toast* toast = new Toast(text, widget);
    toast->show();
}

void Toast::initUI(const QString &text)
{
    // 去除窗口标题, 并将窗口设置为透明背景颜色
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setFixedSize(800,60);

    // 窗口添加背景窗口
    QWidget* toastBg = new QWidget(this);
    toastBg->setFixedSize(800, 60);
    toastBg->setStyleSheet("background-color : rgba(102, 102, 102, 0.5);"
                           "border-radius : 4px");
    // 界面布局
    QVBoxLayout* layout = new QVBoxLayout(toastBg);
    layout->setSpacing(0);
    layout->setContentsMargins(0,0,0,0);
    toastBg->setLayout(layout);

    // 显示文本
    QLabel* label = new QLabel(toastBg);
    label->setText(text);
    label->setAlignment(Qt::AlignCenter);
    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    label->setStyleSheet("font-family: 微软雅黑;"
                         "font-size: 14px;"
                         "color: #FFFFFF;");
    layout->addWidget(label);

    // 设置Toast的窗口位置
    QScreen* screen = QApplication::primaryScreen();
    int width = screen->size().width();
    int height = screen->size().height();
    int x = (width - this->width()) / 2;
    int y = height - this->height() - 100;
    LOG() << x << " " << y << "-" << width << " " << height;
    this->move(x, y);
}
